/* eslint-disable react/jsx-no-bind */
import React, { useState, useEffect, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { Spin, message } from 'choerodon-ui';
import { axios } from '@choerodon/master';
import { Modal } from 'choerodon-ui/pro';
import YamlEditor from '@/components/yamlEditor';
import InterceptMask from '@/components/intercept-mask';
import OpenModifyValueModals from './Models/openModifyModels';

import './index.less';
import { useModifyValuesStore } from './stores';

const valueKey = Modal.key();
const ValueModalContent = observer(() => {
  const {
    modal,
    refresh,
    isMarket,
    isMiddleware,
    instanceId,
    appServiceId,
    appServiceVersionId,
    envId,
    valuesDs,
    valueDs,
    projectId,
    formatMessage,
    prefixCls,
    appDetailTabStore,
  } = useModifyValuesStore();

  const [value, setValue] = useState('');
  const [isDisabled, setIsDisabled] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const yaml = valuesDs.current?.get('yaml');
  const modalStyle = useMemo(() => ({
    width: '540px',
  }), []);
  // 增加文本内容不变时，部署按钮为禁用状态
  useEffect(() => {
    modal.update({
      okProps: {
        disabled: !value,
      },
    });
  }, [value]);
  function upgrade(data:any) {
    const values = valueDs.current?.get('replicasStrategy');
    // eslint-disable-next-line no-param-reassign
    data.replicasStrategy = values;
    const url = isMiddleware
      ? `/devops/v1/projects/${projectId}/middleware/redis/${data.instanceId}`
      : `/devops/v1/projects/${projectId}/app_service_instances${isMarket ? `/market/instances/${data.instanceId}` : ''}`;
    return axios.put(url, JSON.stringify(data));
  }

  async function handleOk() {
    await Modal.open({
      key: valueKey,
      title: formatMessage({ id: `${prefixCls}.modal.values.value` }),
      movable: false,
      style: modalStyle,
      children: <OpenModifyValueModals valueDs={valueDs} count={appDetailTabStore.getCount} />,
      async onOk() {
        if (isDisabled) return false;
        setIsLoading(true);

        const data:any = {
          values: value || yaml || '',
          instanceId,
          type: 'update',
          environmentId: envId,
          appServiceId,
          appServiceVersionId,
        };

        try {
          const res = await upgrade(data);
          if (res && res.failed) {
            message.error('修改失败');
            return false;
          }
          modal.close();
          message.success('修改成功');
          refresh && refresh();
          return true;
        } catch (e) {
          modal.close();
          throw new Error(e);
        }
      },
    });
  }

  function toggleOkDisabled(flag:boolean) {
    modal.update({ okProps: { disabled: flag } });
  }

  function handleChange(nextValue:string) {
    setValue(nextValue);
  }

  function handleEnableNext(flag:boolean) {
    setIsDisabled(flag);
    toggleOkDisabled(flag);
  }

  modal.handleOk(handleOk);

  return (
    <>
      <div className={`${prefixCls}-instance-upgrade-tips`}>
        <strong> 注意！若您修改了下方的Values，需要重新确认此次生效的「副本数量」策略：</strong>
        <span>
          <br />
          - 策略1：根据下方Values来设置「副本数量」。
          <br />
          - 策略2：与Pod详情界面中的「副本数量」保持一致，Values中控制「副本数量」的配置将不会生效。
          <br />
        </span>
      </div>
      <Spin spinning={valuesDs.status === 'loading'}>
        <YamlEditor
          readOnly={false}
          value={value || yaml || ''}
          originValue={yaml}
          onValueChange={handleChange}
          handleEnableNext={handleEnableNext}
        />
      </Spin>
      <InterceptMask visible={isLoading} />
    </>
  );
});

export default ValueModalContent;
